import os
import simplejson
import subprocess
import datetime
 
f = open('latitude.json', 'r')
locdata = simplejson.loads(f.read());
 
fd = open('latitude.gpx', 'w')
fd.write("""# <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1"><trk><name>Google Latitude Export</name><trkseg>""")
lastloc = None
for value in reversed(sorted(locdata['data']['items'])):
    print value
    #raise Exception('def');
    if lastloc:
        timedelta = (int(value['timestampMs']) - int(lastloc['timestampMs'])) / 1000 / 60
        if timedelta > 10:
            # no points for 10 Minutes, Start new Track
            fd.write( "</trkseg><trkseg>")
    fd.write( '<trkpt lat="%s" lon="%s">' % (value['latitude'], value['longitude']))
    fd.write( '<time>%s</time></trkpt>' % str(datetime.datetime.fromtimestamp(int(value['timestampMs'])/1000)).replace(' ', 'T') + 'Z')
    lastloc = value
fd.write( "</trkseg></trk></gpx>")
